# https://www.notion.so/waltz/MySQL-568b0eef22a34f1b882d8ef403b2803d
"""
    获取notion数据
"""
import os
import time
from selenium.webdriver.support import expected_conditions as EC

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

import utils
from utils import check_update_chromedriver

url = "https://www.notion.so/waltz/Web-2f3a6047ca1640fbbb4c9de9aef24828"


class GetNotionData:

    def __init__(self):
        check_update_chromedriver()
        # 杀死这个chromedriver进程，因为每次启动都会打开，所以需要kill，这里用的chrome浏览器，打开方式时chromedriver.exe。需要放在代码同一目录下，不明白的可以搜索
        os.system("taskkill /f /im chromedriver.exe")
        # 定义chrome选项
        options = webdriver.ChromeOptions()
        # 设置选项
        options.add_experimental_option("detach", True)
        # 设置当前driver选项
        self.driver = webdriver.Chrome(options=options)
        # 设置this
        this = self.driver
        this.get("https://www.notion.so/login")  # 先加载网站
        path = r'./config.ini'
        cookies_cfg = utils.read_config(path)
        cookies = cookies_cfg['cookies']['cookie']
        lists = cookies.split(';')
        for i in lists:
            j = i.strip()
            j = j.split('=')
            temp_cookie = {
                'domain': '.notion.so',
                'name': j[0],
                'value': j[1],
                'path': '/',
                'expires': None
            }
            this.add_cookie(temp_cookie)
        this.maximize_window()  # 窗口最大化
        this.get(url)  # 进入对应的网址
        time.sleep(1)

    def notion_query(self):
        this = self.driver
        wait = WebDriverWait(this, 60)
        # 等待登录成功
        wait.until(EC.presence_of_element_located((By.CLASS_NAME, "notion-page-content")))
        print(this.get_cookies())
        # 获取列表
        page_list = this.find_element_by_class_name("notion-page-content").find_elements_by_class_name(
            "notion-selectable")
        for page in range(len(page_list)):
            # print(page_list[page])
            self.page_format(page_list[page])

    def page_format(self, page):
        page.click()
